const nodeRequire = (window as any).nodeRequire;
const dialog = (window as any).dialog;
const fs = nodeRequire('fs');
const pathLib = nodeRequire('path');

export interface IFileInfo {
  path: string;
  name: string;
  extname: string;
  isFolder: boolean;
}

export function loadFile (filePath: string): string {
  return fs.readFileSync(filePath).toString();
}

export function loadFolder (filePath: string): IFileInfo[] {
  const list: string[] = fs.readdirSync(filePath);
  return list.map(name => {
    const path = pathLib.resolve(filePath, name);
    const stat = fs.statSync(path);
    return {
      path,
      name,
      extname: pathLib.extname(name),
      isFolder: stat.isDirectory(),
    };
  });
}

export function writeFile (filePath: string, content: string) {
  fs.writeFileSync(filePath, content);
}

export function getExtName (name: string): string {
  const extname = pathLib.extname(name);
  if (extname?.length >= 2) {
    return extname.substr(1);
  } else {
    return '';
  }
}

const langMap: any = {
  'js': 'javascript',
  'htm': 'html',
  'html': 'html',
  'css': 'css',
  'txt': 'plaintext',
};

export function getLang (extName: string): string {
  const lang = langMap[extName];
  return lang || 'plaintext';
}

export function selectFolder (): Promise<string> {
  return new Promise<string>(resolve => {
    // const inputEle = document.querySelector<HTMLInputElement>('#folder__selector');
    // inputEle.click();
    // inputEle.onchange = () => {
    //   const value = inputEle.value;
    //   inputEle.value = null;
    //   inputEle.onchange = () => {};
    //   resolve(value);
    // }
    dialog.selectFolder().then((result: string) => {
      resolve(result);
    });
  });
}

export function getName (filePath: string): string {
  return pathLib.basename(filePath);
}

export function isSubPath (parentPath: string, subPath: string): boolean {
  const relative = pathLib.relative(parentPath, subPath);
  return relative && !relative.startsWith('..') && !pathLib.isAbsolute(relative);
}